import { Request, errorToast, successToast } from '@/utils'
	let request = new Request()
	export default {
		data () {
			return {
				priceId : 0,
				payTypes : {1 : '扫码支付', 2 : '投币/刷卡'},
				chargeTypes : {1 : '计时', 2 : '计量'},
				rateIndexs : ['一', '二', '三', '四'],
				formData : {
					price_name : '',
					charge_type : 1,
					charge_unit : '',
					max_power : '',
					critical_power : '',
					check_time : '',
					prepayment : '',
					
					options : [],
					class_rate  : [
						{q : '', w : ''},
						{q : '', w : ''},
						{q : '', w : ''},
						{q : '', w : ''}
					]
				},
			}
		},
		
		methods : {
			addPricePre : function(){
				let options = this.formData.options
				let row = options[options.length - 1]
				if(row){
					if(row.q === '' || row.a === '') return
				}
				
				options.push({q : '', a : ''})
			},
			deletePricePre : function(index){
				this.formData.options.splice(index, 1)
			},
			
			submit : function(){
				let formData = Object.assign({}, this.formData)
				let type = formData.type
				if(formData.price_name === '' || formData.charge_unit === '' || formData.critical_power === '' || formData.check_time === '' || formData.prepayment === ''){
					errorToast('请完整填写数据', this)
					return
				}
				
				for(let i in formData.class_rate){
					if(formData.class_rate[i].a === '' || formData.class_rate[i].w === ''){
						errorToast('请完整填写费率', this)
						return
					}
					
					formData.class_rate[i].a = Number(formData.class_rate[i].a)
					formData.class_rate[i].w = Number(formData.class_rate[i].w)
				}
				
				
				for(let i in formData.options){
					if(formData.options[i].a === '' || formData.options[i].q === ''){
						errorToast('请填写完整充电预设选项', this)
						return
					}
					formData.options[i].a = Number(formData.options[i].a)
					formData.options[i].q = Number(formData.options[i].q)
				}

				if(this.priceId > 0){
					formData.price_id = this.priceId
				}
				
				request.post('Price/save', res => {
					if(res.success){
						successToast(res.msg, this)
						this.$router.go(-1)
					}else{
						errorToast(res.msg, this)
					}
				}, formData);
				
			}
		},
		
		created () {
			let priceId = this.$route.params.priceId
			if(priceId){
				this.priceId = priceId
				request.get('Price/getEditInfo', res => {
					if(res.success && res.data){
						let data = res.data
						for(let k in data){
							if(k in this.formData){
								try{
									if(k == 'options' || k == 'class_rate') {
										if(!Array.isArray(data[k])){
											data[k] = JSON.parse(data[k])
										}
									}
								}catch(e){
								}
								this.formData[k] = data[k]
							}
						}
					}else{
						
					}
				}, {id : priceId})
			}
			
		}
		
	}